<template>
    <div class="card" style="margin-bottom:5px">
        <el-upload
                style="display: inline-block;margin:0 10px"
                class="avatar-uploader"
                action="http://localhost:8080/product/import"
                show-file-list="false"
                :on-success="success"
                size="large"
        >
            <el-button type="info" round style="background-color: #5574a5"><el-icon><Folder /></el-icon>  <span>批量导入商品信息</span></el-button>
        </el-upload>
    </div>
    <div class="card" style="padding:30px;margin-bottom:5px">
            <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="100px" style="padding-right:40px;padding-top:20px">
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="data.form.name"  size="large" autocomplete="off" placeholder="请输入商品名称"/>
                </el-form-item>
                <el-form-item label="商品封面">
                    <el-upload
                            class="avatar-uploader"
                            action="http://localhost:8080/files/upload"
                            list-type="picture"
                            :on-success="handleImgSuccess"
                    >
                        <el-button type="img" size="large">上传商品图片</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="商品库存" prop="stock" >
                    <el-input-number
                            v-model="data.form.stock"
                            controls-position="right"
                            placeholder="请输入库存"
                            min="0"
                    />
                </el-form-item>
                <el-form-item label="商品价格" prop="price">
                    <el-input-number v-model="data.form.price" :precision="2" :step="0.1" :min="0" style="width: 200px" >
                        <template #suffix>
                            <span>RMB</span>
                        </template>
                    </el-input-number>
                </el-form-item>
                <el-form-item label="商品一级分类" prop="parentName">
                    <el-select style="width:100%" v-model="data.parentName" size="large" placeholder="请选择一级分类" @change="handleParentNameChange">
                        <el-option  v-for="item in data.classList" :key="item.parentName" :label="item.parentName" :value="item.parentName"  >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品二级分类" prop="childrenname">
                    <el-select style="width:100%" v-model="data.form.category" size="large" placeholder="请选择二级分类" :disabled="!data.parentName">
                        <el-option  v-for="item in data.subClassList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品描述" prop="content">
                        <div style="border: 1px solid #ccc; width: 100%">
                            <Toolbar
                                    style="border-bottom: 1px solid #ccc"
                                    :editor="editorRef"
                                    :mode="mode"/>
                            <Editor
                                    style="height: 500px; overflow-y: hidden;"
                                    v-model="data.form.description"
                                    :mode ="mode"
                                    :defaultConfig="editorConfig"
                                    @onCreated="handlecreated"
                            />

                        </div>

                </el-form-item>
            </el-form>
        <div style="margin-top: 20px;display: flex;justify-content: center;">
            <el-button @click="submitProduct()" size="large" style="width: 80%" type="primary">发布商品</el-button>
        </div>
    </div>
</template>

<script setup>

    import '@wangeditor/editor/dist/css/style.css'//引入css
    import '@/assets/view.css'
    import {onBeforeUnmount,shallowRef} from "vue";
    import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

    import {ElMessage,ElMessageBox} from "element-plus"
    import { reactive,ref } from 'vue';
    import request from "@/utils/request";

    const data = reactive({
        title: null,
        tableData: [],
        form:{},
        ids:[],
        rules:{
                name:[{required:true,message:'请输入商品名称',trigger:'blur'}],
                stock:[{required:true,message:'请输入库存数量',trigger:'blur'}],
                price:[{required:true,message:'请输入商品价格',trigger:'blur'}],
                childrenname:[{ required: true, message: '请选择二级类别', trigger: 'blur' }]
        },
        content:null,
        parentClass:[],
        parentName:null,
        subClassList: [] // 新增，用于存储根据一级分类动态变化的二级分类列表

    });

    /*wangEditor5 初始化开始 */

    const view = (content) =>{
        data.content=content
        data.viewVisable = true
    }

    const success =()=>{
        ElMessage.success('批量导入成功')
    }
    //编辑的对象里面包含id
    const submitProduct= () => {
        request.post('/product/add',data.form).then(
            res =>{
                if(res.code === '200'){
                    ElMessage.success('操作成功')
                    // location.href='/manager/home'
                }else{
                    ElMessage.error(res.msg)
                }
            })
    }

    request.get('/Category/selectParent').then(res =>{
        data.classList = res.data
    })

    // 监听一级分类选择变化，根据所选一级分类获取对应的二级分类列表
    const handleParentNameChange = async (parentName) => {
        if (parentName) {
            try {
                const res = await request.get('/Category/selectAll');
                if (res.code === '200') {
                    const allCategories = res.data;
                    // 根据所选一级分类的parentName筛选出对应的二级分类列表
                    data.subClassList = allCategories.filter(category => category.parentName === parentName);
                    if (data.parentName) {
                        data.form.parentName = data.parentName;
                    }
                } else {
                    ElMessage.error(res.msg);
                }
            } catch (error) {
                console.error(error);
                ElMessage.error('获取二级分类数据失败');
            }
        } else {
            data.subClassList = [];
        }
        data.form.childrenname = null; // 清空二级分类选择
    };
    const baseUrl = 'http://localhost:8080'
    const editorRef = shallowRef()//编辑器实例，必须用 shallowRef
    const mode = 'default'
    const editorConfig = { MENU_CONF:{} }
    //图片上传配置
    editorConfig.MENU_CONF['uploadImage']={
        server: baseUrl+'/files/edit/upload', // 服务端图片上传接口
        fieldName:'file',

    }//服务端图片上传接口参数
    // //组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
    onBeforeUnmount ( () =>{
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
    })
    //记录 editor 实例，重要！
    const handlecreated =(editor) => {
        editorRef.value = editor
    }
    // wangEditor5 初始化结束



    const editContent =(row)=>{
        console.log(row)
        data.form = JSON.parse(JSON.stringify(row))
        data.contentVisible=true
    }


    const handleImgSuccess = (res) =>{
        data.form.imagePath = res.data
    }



    const reset = () => {
        data.name=null
        load()
    }

    const handleAdd = () =>{
        data.FormVisible=true
        data.form={}
    }


    const formRef = ref()

</script>
